'use strict';

const db = uniCloud.database();
const appConfig = {
  appid: 'wxf7abe114e4e3be3f',
  secret: '10688d3dd3c4f3414c9d95edc19369d0'
};

// 获取小程序全局唯一后台接口调用凭据
async function getAccessToken() {
  try {
    // 先从数据库查询是否有未过期的token
    const tokenRecord = await db.collection('access_tokens').orderBy('createTime', 'desc').limit(1).get();
    
    if (tokenRecord.data && tokenRecord.data.length > 0) {
      const token = tokenRecord.data[0];
      // token有效期为2小时，这里用1.5小时作为重新获取的阈值
      if (Date.now() - token.createTime < 5400000) {
        return token.access_token;
      }
    }
    
    // 重新获取token
    const result = await uniCloud.httpclient.request(
      `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appConfig.appid}&secret=${appConfig.secret}`,
      {
        dataType: 'json'
      }
    );
    
    if (!result.data.access_token) {
      throw new Error('获取access_token失败');
    }
    
    // 保存新token到数据库
    await db.collection('access_tokens').add({
      access_token: result.data.access_token,
      createTime: Date.now()
    });
    
    return result.data.access_token;
  } catch (error) {
    console.error('获取access_token失败:', error);
    throw error;
  }
}

exports.main = async (event, context) => {
  try {
    const { scene, page, width = 400 } = event;
    
    console.log('生成小程序码请求参数:', {
      scene,
      page,
      width,
      headers: {
        'Content-Type': 'application/json'
      },
      requestData: {
        scene,
        page,
        width,
        check_path: true,
        env_version: 'release'
      }
    });
    
    // 获取access_token
    const access_token = await getAccessToken();
    console.log('获取到access_token:', access_token);
    
    // 生成小程序码
    console.log('请求微信接口:', `https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=${access_token}`);
    const result = await uniCloud.httpclient.request(
      `https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=${access_token}`,
      {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        data: {
          scene,
          page,
          width,
          check_path: true,
          env_version: 'release'
        },
        dataType: 'buffer'
      }
    );
    
    console.log('微信接口返回:', {
      status: result.data
    });
    
    if (result.status !== 200) {
      console.error('获取小程序码失败:', result);
      throw new Error('获取小程序码失败');
    }
    
    // 上传到云存储
    console.log('开始上传到云存储');
    const uploadResult = await uniCloud.uploadFile({
      cloudPath: `qrcode/${scene}_${Date.now()}.jpg`,
      fileContent: result.data
    });
    
    console.log('上传结果:', uploadResult);
    
    // 记录生成记录到数据库
    await db.collection('qrcode_records').add({
      scene,
      page,
      createTime: Date.now(),
      success: true,
      fileID: uploadResult.fileID
    });
    
    return {
      success: true,
      fileID: uploadResult.fileID
    };
    
  } catch (error) {
    console.error('生成小程序码失败:', error);
    
    // 记录失败记录到数据库
    await db.collection('qrcode_records').add({
      scene: event.scene,
      page: event.page,
      createTime: Date.now(),
      success: false,
      error: error.message
    });
    
    return {
      success: false,
      error: error.message || '未知错误'
    };
  }
}; 